package com.Limiter;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @Package: com.Limiter
 * @ClassName: FixedWindowRateLimiter
 * @Author: h2cloud
 * @CreateTime: 2024/3/16 9:33 下午
 * @Description: 固定窗口时间算法
 */
@Slf4j
public class FixedWindowRateLimiter implements Limiter {

	public int counter = 0;  // 统计请求数
	public long lastAcquireTime = 0L;
	public Long windowSize;    // 窗口大小
	public int limit;   // 窗口阀值是 10

	public FixedWindowRateLimiter(Long windowSize, Integer limit) {
		this.windowSize = windowSize;
		this.limit = limit;
	}

	@Override
	public synchronized boolean tryAcquire() {
		long currentTime = System.currentTimeMillis();  // 获取系统当前时间
		if (currentTime - lastAcquireTime > windowSize) {  // 检查是否在时间窗口内
			counter = 0;  // 计数器清0
			lastAcquireTime = currentTime;  // 开启新的时间窗口
		}
		if (counter < limit) {  // 小于阀值
			counter++;  //计数统计器加1
			return true;
		}

		return false;
	}


	public static void main(String[] args) throws InterruptedException {
		FixedWindowRateLimiter limiter = new FixedWindowRateLimiter(1000L, 5);
		for (int i = 0; i < 100; i++) {
			if (limiter.tryAcquire()) {
				log.info("执行任务");
			} else {
				log.info("被限流");
				TimeUnit.MILLISECONDS.sleep(300);
			}
		}
	}
}
